package com.xuecheng.content.service.impl;

import com.xuecheng.content.mapper.CourseCategoryMapper;
import com.xuecheng.content.model.dto.CourseCategoryTreeDto;
import com.xuecheng.content.model.po.CourseCategory;
import com.xuecheng.content.service.CourseCategoryService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * @Author: chenheng
 * @Date: 2023/12/15 11:26
 */
@Service
@Slf4j
public class CourseCategoryServiceImpl implements CourseCategoryService {
    @Autowired
    CourseCategoryMapper courseCategoryMapper;

    @Override
    public List<CourseCategoryTreeDto> queryTreeNodes(String id) {
        //查询数据库的所有结果
        List<CourseCategoryTreeDto> courseCategoryTreeDtos = courseCategoryMapper.selectTreeNodes(id);
        //定义返回的结果集
        ArrayList<CourseCategoryTreeDto> courseCategoryResult = new ArrayList<>();
        //将courseCategoryTreeDtos转换为map
        Map<String, CourseCategoryTreeDto> mapTemp = courseCategoryTreeDtos.stream().
                filter(item -> !id.equals(item.getId())).
                collect(Collectors.toMap(key -> key.getId(), value -> value, (key1, key2) -> key2));
        //遍历整个courseCategoryTreeDtos
        courseCategoryTreeDtos.stream().filter(item -> !id.equals(item.getId())).forEach(item->{
            //加入二级节点
            if (item.getParentid().equals(id)){
                courseCategoryResult.add(item);
            }
            //找到父节点
            CourseCategoryTreeDto courseCategoryParent = mapTemp.get(item.getParentid());
            if (courseCategoryParent!=null){
                if(courseCategoryParent.getChildrenTreeNodes()==null){
                    courseCategoryParent.setChildrenTreeNodes(new ArrayList<CourseCategoryTreeDto>());
                }
                courseCategoryParent.getChildrenTreeNodes().add(item);
            }
        });
        return courseCategoryResult;
    }
}
